import 'dart:convert';
import 'dart:io';
import 'package:base_flutter/base_flutter.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/models/upload_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:ls_work/widgets/locale_photo_browser.dart';

import '../../util/flat_button.dart';



class HomeLifeEditPage extends StatefulWidget {
  final ElderInfo? info;
  HomeLifeEditPage({Key? key, this.info});
  @override
  _HomeLifeEditPageState createState() => _HomeLifeEditPageState();
}

class _HomeLifeEditPageState extends State<HomeLifeEditPage> {
  TextEditingController textFieldEditer = TextEditingController();
  List<File> imageList = [];
  List<Upload> imagePathList = [];

  String name = '';
  String branchName = '';
  String buildingNo = '';
  String floorNo = '';
  String roomNo = '';
  String nurseLevelName = '';

  @override
  void initState() {
    super.initState();
    name = widget.info?.name ?? '';
    branchName = widget.info?.branchName ?? '';
    buildingNo = widget.info?.buildingNo ?? '';
    floorNo = widget.info?.floorNo?? '';
    roomNo = widget.info?.roomNo ??'';
    nurseLevelName =
        widget.info?.nurseLevelName ??'';
  }

  ///发表
  _sendData() {
    FocusScope.of(context).unfocus();
    if (textFieldEditer.text.isEmpty) {
      Toast.show('请输入发表内容');
      return;
    }
    var map = {
      'customerId': widget.info?.id,
      'elderRoomId': widget.info?.roomId,
      'content': textFieldEditer.text,
    };
    if (imagePathList.length > 0) {
      List temp = [];
      for (var item in imagePathList) {
        var map = {'id': item.id, 'path': item.path};
        temp.add(map);
      }
      map['attaches'] = temp;
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.createCustomerLifeRecord}?${requestParams(map)}')
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          Navigator.pop(context);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('长者生活'),
        elevation: 0.5,
        actions: <Widget>[
          FlatsButton(
            onPressed: _sendData,
            child: Text(
              '发表',
              style: TextStyle(fontSize: 16, color: Colours.app_main),
            ),
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
                width: double.infinity,
                padding: EdgeInsets.fromLTRB(20, 20, 12, 8),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      // LoadAssetImage(
                      //   'mine/me_icon',
                      //   width: 40,
                      //   height: 40,
                      // ),
                      SizedBox(
                        width: 40,
                        height: 40,
                        child: CircleAvatar(
                          backgroundColor: Colors.brown,
                          child: Text('${name.substring(0, 1)}'),
                        ),
                      ),
                      SizedBox(
                        width: 13,
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            width: ScreenUtil.getScreenW(context) - 85,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  name,
                                  style: TextStyles.textBoldDark16,
                                ),
                                SizedBox(
                                  width: 10,
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 5,
                          ),
                          Text(
                            '护理$nurseLevelName' +
                                '级  $branchName  $buildingNo#$floorNo-$roomNo',
                            style: TextStyles.textGray12,
                          ),
                        ],
                      ),
                    ])),
            Container(
              padding: EdgeInsets.all(20),
              color: Colors.white,
              alignment: Alignment.topLeft,
              child: TextField(
                controller: textFieldEditer,
                maxLines: 5,
                maxLength: 150,
                autofocus: false,
                decoration: InputDecoration(
                  hintText: "请输入内容",
                  hintMaxLines: 20,
                  fillColor: Colours.bg_color,
                  filled: true,
                  border: InputBorder.none,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(10, 0, 10, 5),
              child: Text.rich(TextSpan(children: [
                TextSpan(
                  text: '添加图片',
                  style: TextStyles.textDark16,
                ),
                TextSpan(
                  text: '（提示：长按图片可删除图片，最多选择8张图片）',
                  style: TextStyles.textGray12,
                ),
              ])),
            ),
            Gaps.line,
            Container(
              width: ScreenUtil.getScreenW(context),
              height: (ScreenUtil.getScreenW(context) / 4) * 2,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              color: Colors.white,
              child: GridView.builder(
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, //每行三列
                  childAspectRatio: 1.0, //显示区域宽高相等
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemCount: imageList.length + 1,
                itemBuilder: (context, index) {
                  if (index == imageList.length) {
                    return IconButton(
                      onPressed: _pickImageFromSource,
                      icon: LoadAssetImage(
                        "default/add_photo",
                        fit: BoxFit.fill,
                      ),
                    );
                  } else {
                    return InkWell(
                      onTap: () {
                        AppNavigator.push(
                            context,
                            PhotoBrowser(
                              imageLocaleList: imageList,
                              currentPageValue: index,
                            ));
                      },
                      onLongPress: () {
                        _showCupertinoAlertDialog(context, index);
                      },
                      child: Image.file(
                        imageList[index],
                        fit: BoxFit.cover,
                      ),
                    );
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///选择图片方式
  _pickImageFromSource() {
    if (imageList.length == 8) {
      Toast.show('最多上传8张');
      return;
    }
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机"),
                onTap: () async {
                  var imageFile =
                      await ImagePicker().pickImage(source: ImageSource.camera);
                  if(imageFile!=null){
                    setState(() {
                      imageList.add(File(imageFile.path));
                      _upLoadImage(File(imageFile.path));
                    });
                  }
                  Navigator.pop(context);
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("相册"),
                onTap: () async {
                  var imageFile =
                      await ImagePicker().pickImage(source: ImageSource.gallery);
                  if(imageFile!=null){
                    setState(() {
                      imageList.add(File(imageFile.path));
                      _upLoadImage(File(imageFile.path));
                    });
                  }
                  print(imageFile);
                  Navigator.pop(context);
                },
              ),
            ],
          );
        });
  }

  ///上传
  _upLoadImage(File image) async {
    String path = image.path;
    print(path);
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData = new FormData.fromMap({
      'fileType': 'image',
      'fileToUpload': await MultipartFile.fromFile(path, filename: name),
    });
    HttpUtil.instance.getDio().post(HttpApi.upload, data: formData).then((r) {
      ///
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Upload model = Upload.fromJson(map['data']);
            setState(() {
              imagePathList.add(model);
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  void _showCupertinoAlertDialog(BuildContext cxt, int index) {
    showCupertinoDialog<int>(
        context: cxt,
        builder: (cxt) {
          return CupertinoAlertDialog(
            title: Text('提示'),
            content: Text('是否要删除？'),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("确定"),
                onPressed: () {
                  setState(() {
                    imageList.removeAt(index);
                    imagePathList.removeAt(index);
                  });
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ],
          );
        });
  }
}
